﻿#pragma once
#include "HashTable.h"

namespace Map
{
	template <class K, class V, class Hash = HashFunc<K>>
	class unordered_map
	{
		struct MapKeyOpt
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
		
	public:
		typedef typename HashTable<K, pair<const K, V>, MapKeyOpt, Hash >::iterator iterator;

		iterator begin()
		{
			return umap.begin();
		}

		iterator end()
		{
			return umap.end();
		}

		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return umap.Insert(kv);
		}

		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = umap.Insert(make_pair(key, V()));
			return ret.first->second;
		}
	private:
		HashTable<K, pair<const K, V>, MapKeyOpt, Hash> umap;
	};


	void test_map1()
	{
		unordered_map<string, string> dict;
		dict.insert(make_pair("sort", "排序"));
		dict.insert(make_pair("left", "左"));
		dict.insert(make_pair("right", "右"));

		unordered_map<string, string>::iterator it = dict.begin();
		while (it != dict.end())
		{
			cout << it->first << ":" << it->second << endl;
			++it;
		}

		for (auto& kv : dict)
		{
			//kv.first += 'x';
			//kv.second += 'y';
			cout << kv.first << ":" << kv.second << endl;
		}
	}

	void test_map2()
	{
		string arr[] = { "西瓜", "西瓜", "苹果", "西瓜", "苹果", "香蕉", "草莓",
	"香蕉", "草莓", "苹果", "西瓜", "苹果", "草莓" };
		unordered_map<string, int> countMap;
		for (auto& e : arr)
		{
			countMap[e]++;
		}

		for (auto& kv : countMap)
		{
			//kv.first += 'x';
			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;
	}
}